package jwtutils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"scaffold-demo/config"
	"scaffold-demo/utils/log"
	"time"
)

// 1、从config中获取JWT要加密的secret
var jwtSignKet = []byte(config.JwtSignKey)

// 2、自定义声明类型
type MyCustomClaims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

//3、生成token

func GenToken(username string) (string, error) {
	claims := MyCustomClaims{
		"username",
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * time.Duration(config.JwtExpTime))),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "zhouhe",
			Subject:   "zhouhe",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(jwtSignKet)
	return ss, err
}

// 4、解析token
func ParseJwt(ss string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(ss, &MyCustomClaims{},
		func(token *jwt.Token) (interface{}, error) {
			return jwtSignKet, nil
		})
	if err != nil {
		log.Error(nil, "token解析失败")
		return nil, err
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		log.Warning(nil, "token不合法")
		return nil, errors.New("token不合法：invalid token")
	}
}
